package com.zhang.web.filter;


import com.zhang.domain.User;
import com.zhang.service.impl.UserServiceImpl;
import com.zhang.util.CookieUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


@WebFilter({"/communication/*" , "*.jsp"})//拦截性下所有服务 +.jsp页面  (后面放行 login.jsp  和 login服务)
public class AFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("<-------------进入了过滤器--------------->");
        //将父接口转为子接口
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //(1)解决post请求响应乱码
        setUTF(req,resp);


        //(2)过滤请求
        String uri = req.getRequestURI();
        //判断是否是登录页面
        if(uri.contains("/login.jsp")){
            //是登录页面
            chain.doFilter(request,response);//放行
        }else {
            //不是登录页面
            //判断是否登录
            User user = (User) req.getSession().getAttribute("user");
            if(user != null){
                //已登录
                chain.doFilter(request,response);//放行
            }else{
                //未登录过
                //判断cookie中是否有用户名密码
                Cookie cookie = CookieUtil.getCookieByName(req, "remember");
                if(cookie != null){
                    //获取用户名密码
                    String value = URLDecoder.decode(cookie.getValue(),"UTF-8") ;// URLDecoder.decode()url解码
                    String[] usernameAndPass = value.split("#");
                    String username = usernameAndPass[0];
                    String password = usernameAndPass[1];

                    //判断用户名密码是否有效
                    UserServiceImpl userService = new UserServiceImpl();
                    User user2 = userService.findUsernameAndPassword(username, password);
                    if(user2 != null){
                        //密码正确
                        //用户对象保存到session中
                        req.getSession().setAttribute("user",user2);
                        chain.doFilter(request,response);//放行
                    }else{
                        //密码错误 , 跳转到登录页
                        req.setAttribute("msg","请先登录!");
                        req.getRequestDispatcher("/login.jsp").forward(req,resp);//因为这里有数据传递 , 所以必须采用请求转发 (没有数据传递 , 也没有修改数据库 , 就可采用请求重定向)
                    }

                }else {
                    //cookie为空
                    if(uri.contains("/login")){
                        chain.doFilter(request,response);//放行
                    }else {
                        req.setAttribute("msg","请先登录!");
                        req.getRequestDispatcher("/login.jsp").forward(req,resp);//因为这里有数据传递 , 所以必须采用请求转发 (没有数据传递 , 也没有修改数据库 , 就可采用请求重定向)
                    }


                }
            }
        }

    }



    //解决post请求响应乱码
    public void setUTF(HttpServletRequest request, HttpServletResponse response){
        System.out.println("处理请求+响应乱码");
        //获取请求方法
        String method = request.getMethod();


        //(1)解决post请求乱码
        if(method.equalsIgnoreCase("post")){
            try {
                request.setCharacterEncoding("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //(2)处理响应乱码
        response.setContentType("text/html;charset=utf-8");
    }


}
